#!/usr/bin/python
from time import strftime
import sqlite3
import sys
import re
 
import twitter     #http://code.google.com/p/python-twitter/
import bitly       #http://code.google.com/p/python-bitly/
import feedparser  #available at feedparser.org
 
 
DATABASE = "tweets.sqlite"
 
BITLY_LOGIN = "username"
BITLY_API_KEY = "insert_your_key"
 
TWITTER_USER = "username"
TWITTER_PASSWORD = "secret"
 
def print_stats():
	conn = sqlite3.connect(DATABASE)
	conn.row_factory = sqlite3.Row
	c = conn.cursor()
 
	b = bitly.Api(login=BITLY_LOGIN,apikey=BITLY_API_KEY)
 
	c.execute('SELECT title, url, short_url from RSSContent')
	all_links = c.fetchall()
 
	for row in all_links:
 
		short_url = row['short_url']
 
		if short_url is None:
			short_url = b.shorten(row['url'])
			c.execute('UPDATE RSSContent SET `short_url`=? WHERE `url`=?',(short_url,row['url']))
 
 
		stats = b.stats(short_url)
		print "%s - User clicks %s, total clicks: %s" % (row['title'], stats.user_clicks,stats.total_clicks)
 
	conn.commit()
 
def tweet_rss(url):
 	print "Opening database...."
	conn = sqlite3.connect(DATABASE)
	conn.row_factory = sqlite3.Row
	c = conn.cursor()
	print "Database opened."
 
	#create the table if it doesn't exist
	c.execute('CREATE TABLE IF NOT EXISTS RSSContent (`url`, `title`, `dateAdded`, `content`, `short_url`)')
 
	print "Logging in to Twitter...."
	api = twitter.Api(username=TWITTER_USER, password=TWITTER_PASSWORD)
	print "Logging in to Bitly...."
	b = bitly.Api(login=BITLY_LOGIN,apikey=BITLY_API_KEY)
 
	print "Parsing feed...."
	d = feedparser.parse(url)
 
	for entry in d.entries:
 
		#check for duplicates
		c.execute('select * from RSSContent where url=?', (entry.link,))
		if not c.fetchall():
			print entry
			#Get data from this entry
			title = entry.title
			content = entry.content[0].value
			link = entry.link
			updated = entry.updated
			#Strip HTML from content
			r = re.compile(r'<[^<]*?/?>')
			content = r.sub('', content)
			
 			print "Found new item"
			print "Title: "+title
			print "Content: "+content
			print "Link: "+link
			tweet_text = "Buzz: %s" % content
 
 			#Shorten link
			print "Shortening link...."
			shortened_link = b.shorten(link)
			print "Shortened link: "+shortened_link
 
			#Add this entry to the database
			t = (link, title, updated, content, shortened_link)
			c.execute('insert into RSSContent (`url`, `title`,`dateAdded`, `content`, `short_url`) values (?,?,?,?,?)', t)
			print "%s.. %s" % (tweet_text[:115], shortened_link)
 
			#Post to twitter
			print "Posting to twitter...."
			api.PostUpdate("%s.. %s" % (tweet_text[:115], shortened_link))
			print "Post complete."
 
	conn.commit()
 
if __name__ == '__main__':
  tweet_rss(sys.argv[1])
  print "Listing stats...."
  print_stats()
